/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.univaq.iw.jweb;

import it.univaq.iw.jweb.data.Curriculum;
import it.univaq.iw.jweb.data.DataAccess;
import it.univaq.iw.jweb.data.Servizio;
import it.univaq.iw.jweb.utils.SecurityHelpers;
import it.univaq.iw.jweb.utils.TemplateManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author stefano
 */
public class VisualizzaCurriculum extends HttpServlet {
    
    private TemplateManager tpl;
    private DataAccess da;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        da = DataAccess.getInstance();
        tpl = TemplateManager.getInstance(getServletContext());
        tpl.setOutlineTemplate("outline");
        tpl.setDefaultData("author", "Del Vecchio - Bevini - Delfino");
        tpl.setDefaultData("homepage_url", "home");
        
    }

private void selezionaServizi (String email) throws ServletException {

        List<Servizio> servizi = new ArrayList();
        if (email != null && !email.isEmpty()) {

            String nomeGruppo = da.searchNomeGruppo(email);
            servizi = da.searchServiziGruppo(nomeGruppo);

            if (nomeGruppo.equalsIgnoreCase("Candidato")) {
                /* preparo i servizi in base allo stato del candidato */
                Iterator<Servizio> it = servizi.iterator();
                while (it.hasNext()) {
                    Servizio servizio = it.next();
                    if (da.curriculumCompletoByMail(email)) { /* curriculum completato */

                        if (servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                                || (da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("inserisciPreferenze"))) {

                            it.remove();

                        } else if(servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                                || (!da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("modificaPreferenze"))) {

                            it.remove();
                        }

                    } else { /* curriculum incompleto */

                        if (servizio.getNome().equalsIgnoreCase("inserisciPreferenze")
                                || servizio.getNome().equalsIgnoreCase("modificaPreferenze")
                                || servizio.getNome().equalsIgnoreCase("modificaCurriculum")
                                || servizio.getNome().equalsIgnoreCase("visualizzaCurriculum")
                                || servizio.getNome().equalsIgnoreCase("eliminaCurriculum")) {

                            it.remove();
                        }
                    }
                }
            }
            if (nomeGruppo.equalsIgnoreCase("Azienda")) {

                /* preparo i servizi in base allo stato del azienda */
                Iterator<Servizio> it = servizi.iterator();
                while (it.hasNext()) {
                    Servizio servizio = it.next();
                    if (da.hasProfiloRicerca(da.searchPIAziendaByMail(email))) { /* profilo ricerca completato */

                        if (servizio.getNome().equalsIgnoreCase("inserisciProfiloRicerca")) {

                            it.remove();
                        }

                    } else { /* profilo ricerca incompleto */

                        if (servizio.getNome().equalsIgnoreCase("modificaProfiloRicerca")) {

                            it.remove();
                        }
                    }
                }
            }
        }
        tpl.setDefaultData("servizi", servizi);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        HttpSession s = SecurityHelpers.checkSession(request);
        
        if (s == null) {

            selezionaServizi(null);
            tpl.setDefaultData("logged", false);
            PrintWriter out = response.getWriter();

            try {

                Map datamodel = tpl.getDefaultDataModel();

                if (request.getParameterMap().containsKey("id")) { /* */

                    Curriculum curr = da.searchCurriculumById(Integer.parseInt(request.getParameter("id")));

                    datamodel.put("anni",(Calendar.getInstance().getTimeInMillis() - curr.getDataDiNascita().getTime()) / 31536000000L);
                    datamodel.put("curriculum", curr);
                    datamodel.put("idCurriculum", Integer.parseInt(request.getParameter("id")));
                    tpl.process("visualizzaCurriculum", datamodel, out);

                } else {

                    response.sendRedirect("home");
                }

            } finally {
                out.close();
            }

        } else {

            tpl.setDefaultData("logged", true);
            selezionaServizi(s.getAttribute("email").toString());
            PrintWriter out = response.getWriter();

            try {

                Map datamodel = tpl.getDefaultDataModel();

                if (request.getParameterMap().containsKey("id")) { /* */

                    Curriculum curr = da.searchCurriculumById(Integer.parseInt(request.getParameter("id")));

                    if (da.searchNomeGruppo(s.getAttribute("email").toString()).equalsIgnoreCase("Azienda")) {

                        datamodel.put("completo", true);

                        da.aggiornaDataVisualizzazioneAzienda(Integer.parseInt(request.getParameter("id")),da.searchPIAziendaByMail(s.getAttribute("email").toString()));
                    }


                    datamodel.put("anni",(Calendar.getInstance().getTimeInMillis() - curr.getDataDiNascita().getTime()) / 31536000000L);
                    datamodel.put("preferenza", da.searchPreferenzaLavorativa(s.getAttribute("email").toString()));
                    datamodel.put("curriculum", curr);
                    datamodel.put("idCurriculum", Integer.parseInt(request.getParameter("id")));
                    tpl.process("visualizzaCurriculum", datamodel, out);

                } else {

                    int idCurr = da.searchIdCurriculumByMail(s.getAttribute("email").toString());

                    Curriculum curr = da.searchCurriculumById(idCurr);

                    if (curr != null) {

                        datamodel.put("completo", true);

                        datamodel.put("preferenza", da.searchPreferenzaLavorativa(s.getAttribute("email").toString()));
                        datamodel.put("anni",(Calendar.getInstance().getTimeInMillis() - curr.getDataDiNascita().getTime()) / 31536000000L);
                        datamodel.put("curriculum", curr);
                        datamodel.put("idCurriculum", idCurr);
                        tpl.process("visualizzaCurriculum", datamodel, out);

                    } else {
                        datamodel.put("errore", "ATTENZIONE: Non hai nessun curriculum memorizzato!");
                        tpl.process("home", datamodel, out);
                    }
                }

            } finally {
                out.close();
            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
